package com.telchina.common.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.telchina.common.core.domain.AjaxResult;
import com.telchina.common.core.domain.entity.SysUser;
import com.telchina.common.domain.WoTaskConfig;
import com.telchina.common.mapper.WoTaskConfigMapper;
import com.telchina.common.service.IWoTaskConfigService;
import com.telchina.common.utils.DateUtils;
import com.telchina.workorder.domain.WoWorkOrder;
import com.telchina.workorder.service.IWoWorkOrderService;
import com.telchina.workorder.third.service.SystemThirdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * l流程任务配置Service业务层处理
 *
 * @author konghao
 * @date 2023-02-21
 */
@Service
public class WoTaskConfigServiceImpl implements IWoTaskConfigService {

    @Autowired
    private WoTaskConfigMapper woTaskConfigMapper;

    @Autowired
    private SystemThirdService systemThirdService;

    @Autowired
    private IWoWorkOrderService woWorkOrderService;

    /**
     * 查询l流程任务配置
     *
     * @param id l流程任务配置ID
     * @return l流程任务配置
     */
    @Override
    public WoTaskConfig selectById(String id) {
        return woTaskConfigMapper.selectById(id);
    }

    /**
     * 分页查询l流程任务配置列表
     *
     * @param woTaskConfig l流程任务配置
     * @return l流程任务配置
     */
    @Override
    public IPage<WoTaskConfig> selectList(IPage<WoTaskConfig> page, WoTaskConfig woTaskConfig) {
        return woTaskConfigMapper.selectWoTaskConfigPage(page, woTaskConfig);
    }

    /**
     * 查询所有l流程任务配置列表
     *
     * @param woTaskConfig l流程任务配置
     * @return l流程任务配置
     */
    @Override
    public List<WoTaskConfig> selectListAll(WoTaskConfig woTaskConfig) {
        return woTaskConfigMapper.selectWoTaskConfigList(woTaskConfig);
    }

    /**
     * 新增l流程任务配置
     *
     * @param woTaskConfig l流程任务配置
     * @return 结果
     */
    @Override
    public int insert(WoTaskConfig woTaskConfig) {
        woTaskConfig.setCreateTime(DateUtils.getNowDate());

        return woTaskConfigMapper.insert(woTaskConfig);
    }

    /**
     * 修改l流程任务配置
     *
     * @param woTaskConfig l流程任务配置
     * @return 结果
     */
    @Override
    public int update(WoTaskConfig woTaskConfig) {
        woTaskConfig.setUpdateTime(DateUtils.getNowDate());
        return woTaskConfigMapper.updateById(woTaskConfig);
    }

    /**
     * 批量删除l流程任务配置
     *
     * @param ids 需要删除的l流程任务配置ID
     * @return 结果
     */
    @Override
    public AjaxResult deleteByIds(String[] ids) {
        return woTaskConfigMapper.deleteBatchIds(Arrays.asList(ids)) > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 删除l流程任务配置信息
     *
     * @param id l流程任务配置ID
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return woTaskConfigMapper.deleteById(id);
    }

    /**
     * 通过流程key 任务id  和  工单id 获取审批人id
     *
     * @param flowKey
     * @param definitionKey
     * @param workOrderNumber
     */
    @Override
    public String getCandidateUser(String flowKey, String definitionKey, String workOrderNumber) throws Exception {
        // 获取流程配置
        WoTaskConfig woTaskConfig = woTaskConfigMapper.selectOne(new QueryWrapper<WoTaskConfig>().lambda()
                .eq(WoTaskConfig::getDefinitionKey, definitionKey).eq(WoTaskConfig::getFlowKey, flowKey));
        if (ObjectUtil.isEmpty(woTaskConfig)) {
            throw new RuntimeException("流程审批人配置有误");
        }
        // 1：指定部门；2：指定角色;3：指定角色+部门；4：责任单位（工单单号）；5：发起人所在单位（工单单号） 6：发起人所在单位（工单单号） + 角色 7：
        switch (woTaskConfig.getType()){
            case "1":
                List<SysUser> midUserOrg = systemThirdService.getSysUserByDeptId(woTaskConfig.getDeptId());
                if (midUserOrg.size() == 0) {
                    throw new RuntimeException("审批部门下无人员信息");
                }
                return midUserOrg.stream().map(SysUser::getId)
                        .distinct().collect(Collectors.joining(","));
            case "2":
                List<SysUser> midUserRoles = systemThirdService.getSysUserByRoleId(woTaskConfig.getRoleId());
                if (midUserRoles.size() == 0) {
                    throw new RuntimeException("审批角色下无人员信息");
                }
                return midUserRoles.stream().map(SysUser::getId)
                        .distinct().collect(Collectors.joining(","));
            case "3":
                List<SysUser> midUserRoles3 = systemThirdService.getSysUserByRoleId(woTaskConfig.getRoleId());
                if (midUserRoles3.size() == 0) {
                    throw new RuntimeException("审批角色下无人员信息，不可派单");
                }
                List<SysUser> midUserOrg3 = systemThirdService.getSysUserByDeptId(woTaskConfig.getDeptId());
                if (midUserOrg3.size() == 0) {
                    throw new RuntimeException("审批部门下无人员信息");
                }
                List<String> userIdOrg3List = midUserOrg3.stream().map(SysUser::getId)
                        .distinct().collect(Collectors.toList());
                List<String> userIdRole3List = midUserRoles3.stream().map(SysUser::getId)
                        .distinct().collect(Collectors.toList());
                userIdOrg3List.retainAll(userIdRole3List); // 取交集
                return userIdOrg3List.stream().collect(Collectors.joining(","));
            case "4":
                // ①通过工单编号获取工单信息
                WoWorkOrder woWorkOrder = woWorkOrderService.getWorkOrderByWorkOrderNumber(workOrderNumber);
                // 获取责任部门下所有的用户
                List<SysUser> midUserOrg4 = systemThirdService.getSysUserByDeptId(woWorkOrder.getResponsibleUnit());
                if (midUserOrg4.size() == 0) {
                    throw new RuntimeException("派单单位无人员信息，不可派单");
                }
                return midUserOrg4.stream().map(SysUser::getId)
                        .distinct().collect(Collectors.joining(","));
            case "5":
                // ①通过工单编号获取工单信息
                WoWorkOrder woWorkOrder5 = woWorkOrderService.getWorkOrderByWorkOrderNumber(workOrderNumber);
                // 获取责任部门下所有的用户
                List<SysUser> midUserOrg5 = systemThirdService.getSysUserByDeptId(woWorkOrder5.getRegistrantDeptId());
                if (midUserOrg5.size() == 0) {
                    throw new RuntimeException("派单单位无人员信息，不可派单");
                }
                return midUserOrg5.stream().map(SysUser::getId)
                        .distinct().collect(Collectors.joining(","));
            case "6":
                // ①通过工单编号获取工单信息
                WoWorkOrder woWorkOrder6 = woWorkOrderService.getWorkOrderByWorkOrderNumber(workOrderNumber);
                // 获取发起人所在单位下所有的用户
                List<SysUser> midUserOrg6 = systemThirdService.getSysUserByDeptId(woWorkOrder6.getRegistrantDeptId());
                if (midUserOrg6.size() == 0) {
                    throw new RuntimeException("派单单位无人员信息，不可派单");
                }
                List<SysUser> midUserRoles6 = systemThirdService.getSysUserByRoleId(woTaskConfig.getRoleId());
                if (midUserRoles6.size() == 0) {
                    throw new RuntimeException("审批角色下无人员信息，不可派单");
                }
                List<String> userIdOrg6List = midUserOrg6.stream().map(SysUser::getId)
                        .distinct().collect(Collectors.toList());
                List<String> userIdRole6List = midUserRoles6.stream().map(SysUser::getId)
                        .distinct().collect(Collectors.toList());
                userIdOrg6List.retainAll(userIdRole6List); // 取交集
                return userIdOrg6List.stream().collect(Collectors.joining(","));
        }
        return null;
    }

}
